<?php
/*
 *  @autor: peter dobsa
 */
class Courses_model extends CI_Model
{

	//nacita z db kurzy a vrati pole kurzov
	function GetCourses()
	{
		$q = $this->db->get('courses');
		return $q->result();
	}
	
	//vrati kurz podla id-cka ak existuje, ak nie tak vrati 'null'
	function GetCourseById($id)
	{
		$q = $this->db->get_where('courses', array('id' => $id));
		return $q->num_rows() == 0 ? null : $q->first_row();
	}
	
	//prida noveho pouzivatela
	//vstup: meno kurzu
	//vrati uspesnost operacie ako boolean hodnotu
	function InsertCourse($name)
	{
		if ($name == null || strlen($name) == 0) return false;
		return $this->db->insert('courses', array('course_name' => $name));
	}
	
	//aktualizuje meno kurzu s danym id-ckom
	//dostane ako vstup id kurzu a nove meno
	//vrati uspesnost operacie
	function UpdateCourse($id, $name)
	{
		$this->db->where('id', $id);
		return $this->db->update('courses', array('course_name' => $name));
	}
	
	//zmaze pouzivatela s danym idckom
	function RemoveCourse($id)
	{
		$this->db->delete('courses', array('id' => $id));
	}
	
	//prida pouzivatela medzi ucastnikmi zvoleneho kurzu
	//dostane ako parameter id pouzivatela a id kurzu
	//vrati boolovksu hodnotu: ak neexistuje kurz alebo pouzivatel s danym idckom vrati false
	//inak vrati uspesnost operacie
	function EnrollUser($idCourse, $idUser)
	{
		$this->load->model('Users_model', 'users');
		if ($this->users->GetUserById($idUser) == null) return false;
		if ($this->GetCourseById($idCourse) == null) return false;
		return $this->db->insert('enrolled_users', 
			array
			(
				'users_id' => $idUser,
				'courses_id' => $idCourse
			));
	}
	
	//dostane id kurzu a id pouzivatela
	//vrati ako bool ci pouzivatel je zapisany na kurz 
	function IsUserEnrolled($idCourse, $idUser)
	{
		$q = $this->db->where('users_id', $idUser)
			          ->where('courses_id', $idCourse)
					  ->get('enrolled_users');
		return $q->num_rows() != 0;
	}
	
	//vrati pole vsetkych studentov kurzu s danym id-ckom
	function GetEnrolledUsers($id)
	{
		$enrolled = $this->db->where('courses_id', $id)
						     ->get('enrolled_users');
		$arrayOfId = array();
		foreach ($enrolled->result() as $i => $value)
		{
			array_push($arrayOfId, $value->users_id);
		}
		$q = $this->db->query("SELECT * FROM users WHERE id IN (" 
				. implode(',', array_map('intval', $arrayOfId)) . ')');
		return $q->result();
	}
	
	//odstrani pouzivatela z kurzu
	//vrati uspesnot operacie
	function BanUser($idCourse, $idUser)
	{
		if (!$this->IsUserEnrolled($idCourse, $idUser)) return false;
		$this->db->delete('enrolled_users', array(
						'users_id' => $idUser,
						'courses_id' => $idCourse
						));
		return true;
	}

}